from decimal import Decimal
import traceback
from django.http import HttpResponse

from pywebsite.controller_paddleocr import get_ocr_result_by_url
from .forms import SaveFileForm
from .check_receipt import check_receipt_amount_date
import datetime
import os
from .models import SaveFileModel
from pathlib import Path

from pywebsite.util import download_image
import requests

import uuid


BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.join(BASE_DIR,'ReceiptORC')
ReceiptORC_MEDIA_ROOT = os.path.join(PROJECT_ROOT,'imgs')

os.environ['NO_PROXY'] = 'marisfrolg.obs.myhuaweicloud.com,www.baidu.com'

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")




def check_receipt_url(request):
    if request.method == 'POST':
        form = SaveFileForm(request.POST, request.FILES)

        if form.is_valid():
            file_url = form.cleaned_data['fileUrl']
            print(file_url)
            r = requests.get(file_url)

            fileretpath = os.path.join(ReceiptORC_MEDIA_ROOT, file_url.split("/")[len(file_url.split("/"))-1])
            with open(fileretpath, "wb") as code:

                code.write(r.content)
        return HttpResponse(file_url)
    else:
        return HttpResponse("使用POST - form-data调用")

# 日期验证年份
def check_img(request):
    if request.method == 'GET':
        file_url = request.GET.get('url')
    if request.method == 'POST':
        file_url = request.POST.get('url')
    try:
        result = get_ocr_result_by_url(file_url)
        # 生产环境有[0]
        retstr = ""
        for line in result:

            if str(line[1][0]).find("23") >= 0 or str(line[1][0]).find("22") >= 0:
                retstr += str(line[1][0]) + " | "
        return HttpResponse(retstr)
    except Exception as e:
        return HttpResponse("")



def check_receipt(request):
    if request.method == 'POST':
        form = SaveFileForm(request.POST, request.FILES)

        if form.is_valid():
            files = request.FILES.getlist('file')
            file_url = form.cleaned_data['fileUrl']


            fid = "%s" % uuid.uuid4()

            resource_file_name = fid

            if len(files) > 0:
                resource_file_name = files[0].name
            if len(file_url.split("/")) > 1:
                resource_file_name = file_url.split("/")[len(file_url.split("/"))-1]

            amount = form.cleaned_data['amount']
            date = form.cleaned_data['date']
            shop = form.cleaned_data['shop']
            print('check_receipt Accept - datetime : ', date, type(date), ',amount : ', amount)
            filename = datetime.datetime.strftime(date, '%Y-%m-%d') + '-' + "%s" % amount + '-' + fid + '-source-' + resource_file_name
            filepath = os.path.join(ReceiptORC_MEDIA_ROOT, filename)

            # 传的链接-下载图片
            if len(file_url) > 0:
                err, filepath = download_image(file_url, filepath)
                if err:
                    return HttpResponse("图片下载失败,"+err)

            filename_ret = os.path.basename(filepath).replace("-source-", "-ret-")
            filename_err = os.path.basename(filepath).replace("-source-", "-err-")
            name, ext = os.path.splitext(filepath)
            # 检查扩展名的长度
            if not ext or len(ext) > 5:  # 如果没有扩展名或扩展名长度大于5
                filename_ret += '.jpg'  # 添加 .jpg 扩展名
                filename_err += '.jpg'  # 添加 .jpg 扩展名
            fileretpath = os.path.join(ReceiptORC_MEDIA_ROOT, filename_ret)
            fileerrpath = os.path.join(ReceiptORC_MEDIA_ROOT, filename_err)

            # 直接传图
            if len(files) > 0:
                # save_file = SaveFileModel()
                # save_file.save()
                destination = open(filepath, 'wb+')
                if len(files) > 0:
                    for chunk in files[0].chunks():
                        destination.write(chunk)
                    destination.close()

            try:
                ret_code, ret_img = check_receipt_amount_date(amount, date, filepath,shop,debug=request.GET.__contains__('debug'))
                ret_img.save(fileretpath)

                if ret_code == -3:
                    return HttpResponse("小票错误(请不要上传ODS单据),"+"/ReceiptORC/imgs/" + filename_ret)
                if ret_code == 1:
                    return HttpResponse("验证成功,"+"/ReceiptORC/imgs/" + filename_ret)
                # -1金额未匹配，-2日期未匹配，0全部未匹配
                if ret_code == -1:
                    return HttpResponse("金额未匹配,"+"/ReceiptORC/imgs/" + filename_ret)
                if ret_code == -2:
                    return HttpResponse("日期未匹配,"+"/ReceiptORC/imgs/" + filename_ret)
                if ret_code == 0:
                    return HttpResponse("全部未匹配,"+"/ReceiptORC/imgs/" + filename_ret)
                return HttpResponse(ret_code)
            except Exception as e:
                if len(file_url) > 0:
                    if os.path.isfile(filepath):
                        os.rename(filepath, fileerrpath)
                if len(files) > 0:
                    if os.path.isfile(filepath):
                        os.rename(filepath, fileerrpath)
                if os.path.isfile(filepath):
                    os.remove(filepath)
                print(e)
                traceback.print_exc()
                if len(e.args) > 0:
                    return HttpResponse("图片验证失败,报错(可能没有文字):" + e.args[0])
                return HttpResponse("图片验证失败,报错(可能没有文字)")
        return HttpResponse(form.errors)
    else:
        return HttpResponse("使用POST - form-data调用")




